//
//  CompanyViewController.m
//  InviteJob
//
//  Created by LangLang on 17/11/1.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "CompanyViewController.h"

@interface CompanyViewController ()<TZImagePickerControllerDelegate,UIPickerViewDataSource, UIPickerViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *viewCompany;
@property (nonatomic,strong) SZTextView *textView;

@property (weak, nonatomic) IBOutlet UIImageView *iconCompanyLogo;
@property (weak, nonatomic) IBOutlet UIImageView *iconCompanyLicense;
@property (nonatomic, strong)  NSArray *logoArr;
@property (strong, nonatomic)  NSArray *licenseArr;

@property (weak, nonatomic) IBOutlet UITextField *txtName;
@property (weak, nonatomic) IBOutlet UITextField *txtAdress;
@property (weak, nonatomic) IBOutlet UITextField *txtKind;
@property (weak, nonatomic) IBOutlet UITextField *txtNumber;

@end

@implementation CompanyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 读取数据
    [self getDataCompany];
    
    self.mem_province = @"";
    self.mem_city = @"";
    self.mem_country = @"";
    
    
    [self layout];
    
 
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotificiation:) name:@"buttonCompany" object:@"buttonCompany"];
    
   
}
- (void)receiveNotificiation:(NSNotification*)sender{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self updata];
    });
    
}
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"buttonCompany" object:@"buttonCompany"];
    
}

- (void)layout{
    _scrollView.contentSize = CGSizeMake(WIDTH, 598);
    
    [_iconCompanyLogo setUserInteractionEnabled:YES];
    [_iconCompanyLicense setUserInteractionEnabled:YES];
    [_iconCompanyLogo addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickCategory:)]];
    [_iconCompanyLicense addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickCategory:)]];
    
    _textView = [SZTextView new];
    _textView.placeholder = @"请输入公司描述";
    _textView.font = [UIFont systemFontOfSize:14];
    [_viewCompany addSubview:_textView];
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_viewCompany);
    }];
    
    // picker
    self.pickerView = [[RegionPicker alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64-50-10)];
    self.pickerView.pickerView.dataSource = self;
    self.pickerView.pickerView.delegate = self;
    [self.pickerView.confirmButton addTarget:self action:@selector(regionSelectAction) forControlEvents:UIControlEventTouchUpInside];
    [self.pickerView setHidden:YES];
    [self.view addSubview:self.pickerView];
}
-(void)clickCategory:(UITapGestureRecognizer *)gestureRecognizer
{
    UIView *viewClicked=[gestureRecognizer view];
    if (viewClicked==_iconCompanyLogo) {
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos,NSArray *assets,BOOL isSelectOriginalPhoto){
            _logoArr = photos;
            _iconCompanyLogo.image = photos[0];
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
        
    }else if(viewClicked==_iconCompanyLicense)
    {
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos,NSArray *assets,BOOL isSelectOriginalPhoto){
            _licenseArr = photos;
            _iconCompanyLicense.image = photos[0];
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
        
    }
    
}
- (IBAction)btnAdress:(id)sender {
    if(!self.province) {
        
        NSString *jsonPath = [[NSBundle mainBundle]pathForResource:@"region" ofType:@"json"];
        NSData *jsonData = [[NSData alloc]initWithContentsOfFile:jsonPath];
        self.province = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
        self.city = self.province[0][@"city"];
        self.country = self.city[0][@"country"];
        self.mem_province = self.province[0][@"province_code"];
        self.mem_city = self.city[0][@"city_code"];
        self.mem_country = self.country[0][@"country_code"];
        _txtAdress.text = [NSString stringWithFormat:@"%@%@%@",self.province[0][@"province_name"], self.city[0][@"city_name"], self.country[0][@"country_name"]];
        [self.pickerView setHidden:NO];
        [self.pickerView.pickerView reloadAllComponents];
    }else {
        [self.pickerView setHidden:NO];
        [self.pickerView.pickerView reloadAllComponents];
    }
}
- (IBAction)btnCompanyKinds:(id)sender {
    
    NSArray * educationArray = @[@"国企",@"私企",@"中介"];
    zySheetPickerView * pickerView = [zySheetPickerView ZYSheetStringPickerWithTitle:educationArray andHeadTitle:@"公司类型" Andcall:^(zySheetPickerView *pickerView, NSString *choiceString) {
        _txtKind.text = choiceString;
        [pickerView dismissPicker];
    }];
    [pickerView show];
    
}
- (IBAction)btnCompanyNumber:(id)sender {
    
    NSArray * educationArray = @[@"少于15人",@"15~50人",@"50~150人",@"150~500人",@"500人以上"];
    zySheetPickerView * pickerView = [zySheetPickerView ZYSheetStringPickerWithTitle:educationArray andHeadTitle:@"公司规模" Andcall:^(zySheetPickerView *pickerView, NSString *choiceString) {
        _txtNumber.text = choiceString;
        [pickerView dismissPicker];
    }];
    [pickerView show];
}

#pragma mark --数据上传

-(void)navSaveAction:(UIButton *)button{
    NSLog(@"111");
}





// 区域选择确定
- (void)regionSelectAction {
    [self.pickerView setHidden:YES];
    if (self.selectedRegion.length==0) {
        _txtAdress.text = @"北京北京市东城区";
    }else{
        _txtAdress.text = self.selectedRegion;
    }
    self.province_code = self.mem_province;
    self.city_code = self.mem_city;
    self.country_code = self.mem_country;
}

#pragma mark - UIPickerView datasource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    switch (component) {
        case 0:
        {
            if(![self.province isKindOfClass:[NSNull class]]) {
                return self.province.count;
            }else {
                return 0;
            }
        }
            break;
        case 1:
        {
            if(![self.city isKindOfClass:[NSNull class]]) {
                return self.city.count;
            }else {
                return 0;
            }
        }
            break;
        case 2:
        {
            if(![self.country isKindOfClass:[NSNull class]]) {
                return self.country.count;
            }else {
                return 0;
            }
        }
            break;
        default:
            break;
    }
    return 0;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    switch (component) {
            
        case 0:
        {
            // 省份
            return self.province[row][@"simple_province_name"];
        }
            break;
        case 1:
        {
            // 城市
            return self.city[row][@"simple_city_name"];
        }
            break;
        case 2:
        {
            // 乡镇、街道
            return self.country[row][@"simple_country_name"];
        }
            break;
        default:
            break;
    }
    return nil;
}

#pragma mark - UIPickerView delegate
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    switch (component) {
        case 0:
        {
            // 省份
            self.city = self.province[row][@"city"];
            self.country = self.city[0][@"country"];
            [pickerView selectRow:0 inComponent:1 animated:NO];
            [self pickerView:self.pickerView.pickerView didSelectRow:0 inComponent:1];
        }
            break;
        case 1:
        {
            // 城市
            self.country = self.city[row][@"country"];
            [pickerView selectRow:0 inComponent:2 animated:NO];
            [self pickerView:self.pickerView.pickerView didSelectRow:0 inComponent:2];
        }
            break;
        case 2:
        {
            // 乡镇、街道
        }
            break;
        default:
            break;
    }
    
    
    self.mem_province = self.province[[pickerView selectedRowInComponent:0]][@"province_code"];
    self.selectedRegion = self.province[[pickerView selectedRowInComponent:0]][@"province_name"];
    
    self.mem_city = self.city[[pickerView selectedRowInComponent:1]][@"city_code"];
    self.selectedRegion = [self.selectedRegion stringByAppendingString:self.city[[pickerView selectedRowInComponent:1]][@"city_name"]];
    
    if([self.country isKindOfClass:[NSArray class]]) {
        self.mem_country = self.country[[pickerView selectedRowInComponent:2]][@"country_code"];
        self.selectedRegion = [self.selectedRegion stringByAppendingString:self.country[[pickerView selectedRowInComponent:2]][@"country_name"]];
    }else {
        self.mem_country = @"1";
    }
    
    [pickerView reloadAllComponents];
}


#pragma mark --数据上传

-(void)updata{
   
    
    if (_txtName.text.length==0) {
        SHuiMBhudTextTimeStr(@"请填写公司名称");
        return;
    }
    
    if (_txtAdress.text.length==0) {
        SHuiMBhudTextTimeStr(@"请选择所在区域");
        return;
    }
    
    if (_txtKind.text.length==0) {
        SHuiMBhudTextTimeStr(@"请选择公司类型");
        return;
    }
    
    if (_txtNumber.text.length==0) {
        SHuiMBhudTextTimeStr(@"请选择公司规模");
        return;
    }
    
    if (_textView.text.length==0) {
        SHuiMBhudTextTimeStr(@"请输入公司描述");
        return;
    }
    
    NSString *strUrl = [NSString stringWithFormat:post_completeInfo_api];
    
    isUser
    NSDictionary *parameter = @{@"user_id":user.user_id,
                                @"token":user.token,
                                @"type":@"company",
                                @"province":_province_code,
                                @"city":_city_code,
                                @"county":_country_code,
                                @"com_type":_txtKind.text,
                                @"staff_number":_txtNumber.text,
                                @"company_brief":_textView.text,
                                @"company_name":_txtName.text};
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json",@"text/javascript",nil];
    manager.requestSerializer.timeoutInterval = 10;
    [MBProgressHUD showMessag:@"保存中..." withDelay:0 toView:self. view withMode:MBProgressHUDModeIndeterminate hideWithDelay:0];
    [manager POST:strUrl parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (_logoArr.count!=0) {
            NSData *imageData = [self compressOriginalImage:_logoArr[0] toMaxDataSizeKBytes:200];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.png",str];
            [formData appendPartWithFileData:imageData
                                        name:@"company_logo"
                                    fileName:fileName
                                    mimeType:@"image/png"];
        }
        
        if (_licenseArr.count!=0) {
            NSData *imageData = [self compressOriginalImage:_licenseArr[0] toMaxDataSizeKBytes:200];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.png",str];
            [formData appendPartWithFileData:imageData
                                        name:@"license"
                                    fileName:fileName
                                    mimeType:@"image/png"];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",data);
        SHuiMBHidleYes
        if ([data[@"code"] intValue] == 200) {
            SHuiMBhudTextTimeStr(@"认证提交成功，正在审核中");
        }else{
            SHuiMBhudTextTimeStr(data[@"mark"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        SHuiMBHidleYes
        SHuiMBhudTextTimeStr(@"网络异常");
    }];
    
}

//图片压缩到指定大小
/**
 *  压缩图片到指定文件大小
 *
 *  @param image 目标图片
 *  @param size  目标大小（最大值）
 *
 *  @return 返回的图片文件
 */
- (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{
    NSData * data = UIImageJPEGRepresentation(image, 1.0);
    CGFloat dataKBytes = data.length/1000.0;
    CGFloat maxQuality = 0.9f;
    CGFloat lastData = dataKBytes;
    while (dataKBytes > size && maxQuality > 0.01f) {
        maxQuality = maxQuality - 0.01f;
        data = UIImageJPEGRepresentation(image, maxQuality);
        dataKBytes = data.length / 1000.0;
        if (lastData == dataKBytes) {
            break;
        }else{
            lastData = dataKBytes;
        }
    }
    return data;
}


#pragma mark --  获取数据

-(void)getDataCompany{
    isUser
    NSString *strUrl = [NSString stringWithFormat:post_authen_getInfo_api];
    NSDictionary *parameter = @{@"user_id":user.user_id, @"token":user.token};
    [PostNetWorking postNetWorkingStr:strUrl andparameters:parameter Success:^(id responseObject) {
        int code = [responseObject[@"code"]intValue];
        switch (code) {
            case 200:
            {
                
                if ([responseObject[@"datas"][@"type"] isEqualToString:@"company"]) {
                    [_iconCompanyLogo sd_setImageWithURL:[NSURL URLWithString:responseObject[@"datas"][@"company_logo"]]];
                    [_iconCompanyLicense sd_setImageWithURL:[NSURL URLWithString:responseObject[@"datas"][@"license"]]];
                    _txtName.text = responseObject[@"datas"][@"company_name"];
                    _txtAdress.text = [NSString stringWithFormat:@"%@%@%@",responseObject[@"datas"][@"province_name"],responseObject[@"datas"][@"city_name"],responseObject[@"datas"][@"county_name"]];
                    _txtKind.text = responseObject[@"datas"][@"com_type"];
                    _txtNumber.text = responseObject[@"datas"][@"staff_number"];
                    _textView.text = responseObject[@"datas"][@"company_brief"];
                    _country_code = responseObject[@"datas"][@"county"];
                    _city_code = responseObject[@"datas"][@"city"];
                    _province_code = responseObject[@"datas"][@"province"];
                    
                }else{
                    return ;
                }
                
                
            }
                break;
            case 210:
            {
                //逻辑错误
                [MBProgressHUD showMessag:responseObject[@"mark"] withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
            }
                break;
            case 220:
            {
                //token过期
                [MBProgressHUD showMessag:@"登录状态已过期，请重新登录" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
            }
            default:
                break;
        }
        
    } failed:^(NSError *error) {
        [MBProgressHUD showMessag:@"网络错误" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
    }];
}




@end













